package logic

import (
	"bluebell/dao/mysql"
	"bluebell/dao/redis"
	"bluebell/models"
	"bluebell/pkg/jwt"
	"bluebell/pkg/snowflake"
)

// SignUp 注册
func SignUp(params *models.ParamSignUp) (token string, err error) {
	// 1.判断用户存不存在
	if err = mysql.CheckUserExist(params.Phone); err != nil {
		return
	}
	// 2.生成UID
	userID := snowflake.GenID()
	// 3.保存进数据库
	user := &models.User{
		UserID:   userID,
		Phone:    params.Phone,
		Password: params.Password,
	}
	if err = mysql.InsertUser(user); err != nil {
		return
	}
	return jwt.GetToken(user.UserID, user.Phone) // 生成JWT
}

// Login 登录
func Login(params *models.ParamLogin) (res interface{}, err error) {
	user := &models.User{}
	if user, err = mysql.Login(params); err != nil {
		return
	}

	var token string
	if token, err = jwt.GetToken(user.UserID, user.Phone); err != nil { // 生成JWT
		return
	}

	userInfo := map[string]string{}
	userInfo, err = GetUserInfo(user.UserID)
	res = map[string]interface{}{"token": token, "data": userInfo}
	return
}

// GetUserInfo 用户信息
func GetUserInfo(uid int64) (userInfo map[string]string, err error) {
	user := &models.User{}
	user, err = mysql.GenUserById(uid)
	userInfo = redis.SetUserInfoInRedis(user.UserID, user)
	return
}
